const api = require('../../../utils/api')

Page({
  data: {
    order: null,
    paymentMethods: [
      {
        id: 'wxpay',
        name: '微信支付',
        icon: '/images/icons/wxpay.png'
      }
    ],
    selectedMethod: 'wxpay',
    countdown: 900, // 15分钟支付倒计时
    timer: null,
    orderNo: '',
    totalAmount: '',
    isLoading: false
  },

  onLoad(options) {
    const { orderId, orderNo } = options;
    if (!orderId && !orderNo) {
      this.showError();
      return;
    }

    // 从后端获取订单信息
    this.loadOrderInfo(orderNo || orderId);
  },

  // 加载订单信息
  async loadOrderInfo(orderNoOrId) {
    try {
      const res = await api.getCustomerOrder(orderNoOrId);
      if (res.success) {
        this.setData({ 
          order: res.data,
          orderNo: res.data.orderNo,
          totalAmount: res.data.totalAmount.toFixed(2)
        });
        this.startCountdown();
      } else {
        this.showError();
      }
    } catch (error) {
      console.error('加载订单信息失败:', error);
      this.showError();
    }
  },

  onUnload() {
    // 清除定时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  // 开始倒计时
  startCountdown() {
    this.data.timer = setInterval(() => {
      if (this.data.countdown > 0) {
        this.setData({
          countdown: this.data.countdown - 1
        });
      } else {
        clearInterval(this.data.timer);
        // 订单超时，自动取消
        this.cancelOrder();
      }
    }, 1000);
  },

  // 格式化倒计时显示
  formatCountdown() {
    const minutes = Math.floor(this.data.countdown / 60);
    const seconds = this.data.countdown % 60;
    return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  },

  // 选择支付方式
  selectPaymentMethod(e) {
    const { method } = e.currentTarget.dataset;
    this.setData({
      selectedMethod: method
    });
  },

  // 确认支付
  async confirmPayment() {
    const { orderNo } = this.data
    if (!orderNo) {
      wx.showToast({
        title: '订单号不能为空',
        icon: 'none'
      })
      return
    }

    this.setData({ isLoading: true })

    try {
      const res = await api.payOrder(orderNo)
      if (res.success) {
        wx.showToast({
          title: '支付成功',
          icon: 'success'
        })
        
        // 支付成功后清空购物车中对应的商品
        try {
          // 获取结算的商品ID
          const orderItems = wx.getStorageSync('orderCheckoutItems');
          if (orderItems && orderItems.length > 0) {
            // 调用API从购物车中删除已支付的商品
            await api.removeItemsFromCart(orderItems);
            // 清除临时存储
            wx.removeStorageSync('orderCheckoutItems');
          }
        } catch (clearError) {
          console.error('清空购物车失败:', clearError);
          // 购物车清空失败不影响订单支付成功
        }
        
        // 延迟跳转到订单列表页
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/order/order?status=2'
          })
        }, 1500)
      } else {
        throw new Error(res.message || '支付失败')
      }
    } catch (error) {
      console.error('支付失败:', error)
      wx.showToast({
        title: error.message || '支付失败',
        icon: 'none'
      })
    } finally {
      this.setData({ isLoading: false })
    }
  },

  // 取消订单
  async cancelOrder() {
    const { order } = this.data;
    try {
      const res = await api.cancelCustomerOrder(order.orderNo);
      if (res.success) {
        wx.showToast({
          title: '订单已取消',
          icon: 'none'
        });

        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        throw new Error(res.message || '取消订单失败');
      }
    } catch (error) {
      console.error('取消订单失败:', error);
      wx.showToast({
        title: error.message || '取消订单失败',
        icon: 'none'
      });
    }
  },

  // 显示错误提示
  showError() {
    wx.showToast({
      title: '订单不存在',
      icon: 'error'
    });
    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
  }
}); 